package nju.software.xkxt.data.dao.implement;

import java.util.ArrayList;
import java.util.List;

import nju.software.xkxt.data.dao.SelectionDao;
import nju.software.xkxt.data.dataobject.SelectionDO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * @author typ
 * 
 */
public class SelectionDaoImpl extends HibernateDaoSupport implements
		SelectionDao {

	public List<SelectionDO> getSelectionDOByUserId(int userId) {
		String hql = "from SelectionDO where userId=" + userId;
		@SuppressWarnings("unchecked")
		List<SelectionDO> selectionDOList = getHibernateTemplate().find(hql);
		if (selectionDOList == null) {
			selectionDOList = new ArrayList<SelectionDO>();
		}
		return selectionDOList;
	}

	public List<SelectionDO> getSelection() {
		String hql = "from SelectionDO";
		@SuppressWarnings("unchecked")
		List<SelectionDO> selectionDOList = getHibernateTemplate().find(hql);
		if (selectionDOList == null) {
			selectionDOList = new ArrayList<SelectionDO>();
		}
		return selectionDOList;
	}

	public Long getNumByCourseId(int CourseId) {
		String hql = "select count(id) from SelectionDO where courseId = "
				+ CourseId + "and state = 1";
		Session session = this.getSession();
		Query query = session.createQuery(hql);
		Long num = (Long) query.uniqueResult();
		session.close();
		return num;
	}

	@Override
	public boolean delete(int courseId) {
		String sql = "delete from SelectionDO where courseId=:cid";
		Session session = this.getSession();
		boolean b;
		try {
			Query query = session.createQuery(sql);
			query.setParameter("cid", courseId);
			query.executeUpdate();
			b = true;
		} catch (Exception e) {
			b = false;
		}
		return b;
	}

	public Boolean updateEntryByCidAndUid(int cid, int uid, int state) {
		List<SelectionDO> selectionList = getSelectionDOByUserId(uid);
		SelectionDO toUpdateDo = null;
		for (SelectionDO sDo : selectionList) {
			if (sDo.getCourseId() == cid) {
				sDo.setState(state);
				toUpdateDo = sDo;
			}
		}
		if (toUpdateDo == null)
			return false;
		else {
			getHibernateTemplate().update(toUpdateDo);
			return true;
		}
	}
}
